package com.ztools;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangxuehui on 2018/6/11.
 */

public class TestDemo {


    private List<String> list;
    private Map<String, Object> map;

    /***
     * 获取List中的泛型
     */
    public static void testList() throws NoSuchFieldException, SecurityException {
        Type t = TestDemo.class.getDeclaredField("list").getGenericType();
        if (ParameterizedType.class.isAssignableFrom(t.getClass())) {
            for (Type t1 : ((ParameterizedType) t).getActualTypeArguments()) {
                System.out.print(t1 + ",");
            }
            System.out.println();
        }
    }

    /***
     * 获取Map中的泛型
     */
    public static void testMap() throws NoSuchFieldException, SecurityException {
        Type t = TestDemo.class.getDeclaredField("map").getGenericType();
        if (ParameterizedType.class.isAssignableFrom(t.getClass())) {
            for (Type t1 : ((ParameterizedType) t).getActualTypeArguments()) {
                System.out.print(t1 + ",");
            }
            System.out.println();
        }
    }

    public static void getClassType(Class cls) {
        System.out.println(">>>>>>>>>>>" + cls.getTypeParameters() + ">>>>>>>>>>>");
    }

    public static void main(String args[]) throws Exception {
        getClassType(Integer.class);

        System.out.println(">>>>>>>>>>>testList>>>>>>>>>>>");
        testList();
        System.out.println("<<<<<<<<<<<testList<<<<<<<<<<<\n");
        System.out.println(">>>>>>>>>>>testMap>>>>>>>>>>>");
        testMap();
        System.out.println("<<<<<<<<<<<testMap<<<<<<<<<<<\n");
        System.out.println(">>>>>>>>>>>testClassA>>>>>>>>>>>");
        new ClassA<Integer>().testClassA();
        System.out.println("<<<<<<<<<<<testClassA<<<<<<<<<<<");
    }

    public static class ClassA<T> {
        private T obj;

        public void setObject(T obj) {
            this.obj = obj;
        }

        public T getObject() {
            return obj;
        }

        /**
         * 获取T的实际类型
         */
        public void testClassA() throws NoSuchFieldException, SecurityException {
            System.out.print("getSuperclass:");
            System.out.println(this.getClass().getSuperclass().getName());
            System.out.print("getGenericSuperclass:");
            Type t = this.getClass().getGenericSuperclass();
            System.out.println(t);
            if (ParameterizedType.class.isAssignableFrom(t.getClass())) {
                System.out.print("getActualTypeArguments:");
                for (Type t1 : ((ParameterizedType) t).getActualTypeArguments()) {
                    System.out.print(t1 + ",");
                }
                System.out.println();
            }
        }
    }
}
